package com.example.systemwork.entity;

import com.example.systemwork.common.entity.LogicEntity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.Where;

import javax.persistence.*;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;

@Entity
@Getter
@Setter
@Where(clause = "is_deleted = 0")
public class Torder extends LogicEntity {
    //0未支付 1已支付 2已确认 3已退款
    @Column
    private Integer status;

    @ManyToOne(fetch = FetchType.LAZY)
    @JsonIgnoreProperties(value = {"torders"})
    private Customer customer;

    @ManyToOne(fetch = FetchType.LAZY)
    @JsonIgnoreProperties(value = {"torders"})
    private Shop shop;

    @OneToMany(mappedBy = "torder",
            fetch = FetchType.LAZY,
            cascade = CascadeType.ALL)
    @JsonIgnoreProperties(value = {"item","torder"})
    private Set<LineItem> lineItems;

    private LineItem findLineItem(Item item){
        AtomicReference<LineItem> result= new AtomicReference<>(null);
        lineItems.forEach(lineItem ->{
            if(lineItem.getItem().equals(item)){
                result.set(lineItem);
            }
        });
        return result.get();
    }

    public void addItem(Item item,Double quantity){
        LineItem lineItem=findLineItem(item);
        if(lineItem==null){
            lineItem=new LineItem();
            lineItem.setItem(item);
            lineItem.setQuantity(quantity);
            lineItem.setTorder(this);
            lineItem.setItemName(item.getItemName());
            lineItem.setPrice(item.getPrice());
            lineItems.add(lineItem);
        }
        else{
            lineItem.setQuantity(lineItem.getQuantity()+quantity);
        }
    }
    public void addItem(Item item){
        addItem(item,1.0);
    }

    public LineItem removeItem(Item item){
        LineItem lineItem=findLineItem(item);
        if(lineItem!=null){
            lineItems.remove(lineItem);
        }
        return lineItem;
    }
}
